package com.example.qrcodecamera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import android.view.View;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.DecodeHintType;

public class WeightRecordDecodeActivity extends AppCompatActivity {
    private static final int CAMERA_PERMISSION_REQUEST = 100; // 权限请求码

    private EditText  etDate, etbatchNumber, etNumber,etWeight1,  etWeight2, etWeight3;



    private EditText etSearchMaterialId;
    private TextView tvQueryResult;
    private Button btnSave,btnsavemysql;
    private CSVDataDbHelper dbHelpercsv;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight_record_decode);

        btnSave = findViewById(R.id.btn_save);
        btnsavemysql = findViewById(R.id.btn_save_mysql);
        dbHelpercsv = new CSVDataDbHelper(this);
        dbHelper = new DatabaseHelper(this);
        Button btnviewsql =  findViewById(R.id.btn_view_mysqldata);

        // 初始化视图
        Button btnScan = findViewById(R.id.btn_scan);
        Button btnBack = findViewById(R.id.btn_back);
        etDate = findViewById(R.id.et_date);
        etWeight1 = findViewById(R.id.et_weight1);
        etNumber = findViewById(R.id.et_number);
        etWeight2 = findViewById(R.id.et_weight2);
        etbatchNumber = findViewById(R.id.et_batchnumber);
        etWeight3 = findViewById(R.id.et_weight3);


        // 动态请求摄像头权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST
            );
        }

        // 扫描按钮点击事件
        btnScan.setOnClickListener(v -> startOptimizedScanner());

        // 返回按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WeightRecordDecodeActivity.this, MidadminActivity.class);
                startActivity(intent);
                finish();
            }
        });

        btnSave.setOnClickListener(v -> {
            String date = etDate.getText().toString().trim();
            String batch = etbatchNumber.getText().toString().trim();
            String number = etNumber.getText().toString().trim();
            String w1 = etWeight1.getText().toString().trim();
            String w2 = etWeight2.getText().toString().trim();
            String w3 = etWeight3.getText().toString().trim();

            if (date.isEmpty() || batch.isEmpty() || number.isEmpty() ||
                    w1.isEmpty() || w2.isEmpty() || w3.isEmpty()) {
                Toast.makeText(this, "请先扫描完整的二维码数据", Toast.LENGTH_SHORT).show();
                return;
            }

            boolean isInserted = dbHelper.insertData(date, batch, number, w1, w2, w3);
            if (isInserted) {
                Toast.makeText(this, "数据保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });

        btnsavemysql.setOnClickListener(v -> {
            String date = etDate.getText().toString().trim();
            String batch = etbatchNumber.getText().toString().trim();
            String number = etNumber.getText().toString().trim();
            String w1 = etWeight1.getText().toString().trim();
            String w2 = etWeight2.getText().toString().trim();
            String w3 = etWeight3.getText().toString().trim();

            if (date.isEmpty() || batch.isEmpty() || number.isEmpty() ||
                    w1.isEmpty() || w2.isEmpty() || w3.isEmpty()) {
                Toast.makeText(this, "请先扫描完整的二维码数据", Toast.LENGTH_SHORT).show();
                return;
            }

            boolean isInserted = dbHelper.insertMysqlData(date, batch, number, w1, w2, w3);
            if (isInserted) {
                Toast.makeText(this, "数据保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });


        Button btnViewData = findViewById(R.id.btn_view_data);
        btnViewData.setOnClickListener(v -> {
            startActivity(new Intent(this, ViewDataActivity.class));
        });

        btnviewsql.setOnClickListener(v -> {
            startActivity(new Intent(this, ViewDataActivity.class));
        });

        etSearchMaterialId = findViewById(R.id.et_search_material_id);
        tvQueryResult = findViewById(R.id.tv_query_result);
        Button btnSearch = findViewById(R.id.btn_search);

        // 设置查询按钮点击事件
        btnSearch.setOnClickListener(v -> searchRecordsByMaterialId());
    }

    /**
     * 启动优化后的扫描器
     */
    private void startOptimizedScanner() {
        new IntentIntegrator(this)
                .setPrompt("扫描称重记录二维码")
                .setOrientationLocked(true)
                .setBeepEnabled(false)          // 关闭提示音
                .setBarcodeImageEnabled(false)  // 禁用图像保存
                .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) // 仅识别二维码
                .initiateScan();
    }

    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "未授予摄像头权限，无法扫描", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 处理扫描结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null && result.getContents() != null) {
            String rawData = result.getContents();
            // 显示原始结果


            // 清理数据（移除大括号和空格）
            String cleanData = rawData.replaceAll("[{} ]", "").replaceAll("kg", ""); // 新增移除 "kg"
            String[] parts = cleanData.split(",");

            if (parts.length == 6) {
                etDate.setText(parts[0].trim());
                etbatchNumber.setText(parts[1].trim());
                etNumber.setText(parts[2].trim());
                etWeight1.setText(parts[3].trim());
                etWeight2.setText(parts[4].trim());
                etWeight3.setText(parts[5].trim());

                //自动获取批次号并触发查询
                //  String batchNumber = parts[1].trim();
                //   searchRecordsByNumber(batchNumber); // 调用修改后的方法
                String batchNumber = parts[2].trim();
                if (!batchNumber.isEmpty()) {
                    searchRecordsByNumber(batchNumber);
                    showProgressDialog(); // 新增加载提示
                }
            } else {
                Toast.makeText(this, "二维码格式错误，需包含6个字段", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void showProgressDialog() {
        runOnUiThread(() ->
                Toast.makeText(this, "正在查询数据库...", Toast.LENGTH_SHORT).show()
        );
    }


    private void searchRecordsByMaterialId() {
        String materialId = etSearchMaterialId.getText().toString().trim();
        if (materialId.isEmpty()) {
            Toast.makeText(this, "请输入物料编号", Toast.LENGTH_SHORT).show();
            return;
        }

        if (materialId.isEmpty()) {
            Toast.makeText(this, "批次号为空，无法查询", Toast.LENGTH_SHORT).show();
            return;
        }

        List<CSVRecord> records = dbHelpercsv.getRecordsByMaterialId(materialId);
        if (records.isEmpty()) {
            tvQueryResult.setText("未找到相关记录");
            return;
        }

        // 获取当前输入框的值
        String currentBatch = etbatchNumber.getText().toString().trim();
        String currentNumber = etNumber.getText().toString().trim();
        String currentGrossWeight = etWeight1.getText().toString().trim().replaceAll("[^\\d.]", ""); // 移除非数字字符
        String currenttareWeight = etWeight2.getText().toString().trim().replaceAll("[^\\d.]", "");
        String currentNetWeight = etWeight3.getText().toString().trim().replaceAll("[^\\d.]", "");

        // 假设比较最新一条记录
        CSVRecord latestRecord = records.get(0);
        String recordBatch = latestRecord.getBatch();
        String recordNumber = latestRecord.getMaterialId();
        double recordGross = latestRecord.getGrossWeight();
        double recordTare = latestRecord.getTareWeight();
        double recordNet = latestRecord.getNetWeight();

        // 重置所有输入框背景
        resetEditTextBackgrounds();


        // 比较批次号（字符串比较）
        if (!currentBatch.equals(recordBatch)) {
            etbatchNumber.setBackgroundResource(R.drawable.edittext_border_red);
        }

        try {
            double Dtareweight = Double.parseDouble(currenttareWeight);
            if (Dtareweight != recordTare) {
                etWeight2.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            etWeight2.setBackgroundResource(R.drawable.edittext_border_red); // ✅ 正确
        }

        // 比较总重量（数值比较）
        try {
            double currentGross = Double.parseDouble(currentGrossWeight);
            if (currentGross != recordGross) {
                etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            // 输入格式错误，标记为不一致
            etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
        }

        // 比较净重（数值比较）
        try {
            double currentNet = Double.parseDouble(currentNetWeight);
            if (currentNet != recordNet) {
                etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            // 输入格式错误，标记为不一致
            etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
        }

        // 显示查询结果
        StringBuilder resultBuilder = new StringBuilder();
        for (CSVRecord record : records) {
            resultBuilder.append("物料编号: ").append(record.getMaterialId()).append("\n")
                    .append("批次号: ").append(record.getBatch()).append("\n")
                    .append("总重量: ").append(record.getGrossWeight()).append("\n")
                    .append("净重: ").append(record.getNetWeight()).append("\n")
                    .append("时间: ").append(record.getTimestamp()).append("\n\n");
        }
        tvQueryResult.setText(resultBuilder.toString());
    }

    private void resetEditTextBackgrounds() {
        etbatchNumber.setBackgroundResource(R.drawable.edittext_border);
        etWeight1.setBackgroundResource(R.drawable.edittext_border);
        etWeight3.setBackgroundResource(R.drawable.edittext_border);
    }


    private void searchRecordsByNumberlocal(String materialId) {
        //  String materialId = etSearchMaterialId.getText().toString().trim();
        //   if (materialId.isEmpty()) {
        //       Toast.makeText(this, "请输入物料编号", Toast.LENGTH_SHORT).show();
        //       return;
        //   }

        if (materialId.isEmpty()) {
            Toast.makeText(this, "批次号为空，无法查询", Toast.LENGTH_SHORT).show();
            return;
        }

        List<CSVRecord> records = dbHelpercsv.getRecordsByMaterialId(materialId);
        if (records.isEmpty()) {
            tvQueryResult.setText("未找到相关记录");
            return;
        }

        // 获取当前输入框的值
        String currentBatch = etbatchNumber.getText().toString().trim();
        String currentNumber = etNumber.getText().toString().trim();
        String currentGrossWeight = etWeight1.getText().toString().trim().replaceAll("[^\\d.]", ""); // 移除非数字字符
        String currenttareWeight = etWeight2.getText().toString().trim().replaceAll("[^\\d.]", "");
        String currentNetWeight = etWeight3.getText().toString().trim().replaceAll("[^\\d.]", "");

        // 假设比较最新一条记录
        CSVRecord latestRecord = records.get(0);
        String recordBatch = latestRecord.getBatch();
        String recordNumber = latestRecord.getMaterialId();
        double recordGross = latestRecord.getGrossWeight();
        double recordTare = latestRecord.getTareWeight();
        double recordNet = latestRecord.getNetWeight();

        // 重置所有输入框背景
        resetEditTextBackgrounds();


        // 比较批次号（字符串比较）
        if (!currentBatch.equals(recordBatch)) {
            etbatchNumber.setBackgroundResource(R.drawable.edittext_border_red);
        }

        try {
            double Dtareweight = Double.parseDouble(currenttareWeight);
            if (Dtareweight != recordTare) {
                etWeight2.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            etWeight2.setBackgroundResource(R.drawable.edittext_border_red); // ✅ 正确
        }

        // 比较总重量（数值比较）
        try {
            double currentGross = Double.parseDouble(currentGrossWeight);
            if (currentGross != recordGross) {
                etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            // 输入格式错误，标记为不一致
            etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
        }

        // 比较净重（数值比较）
        try {
            double currentNet = Double.parseDouble(currentNetWeight);
            if (currentNet != recordNet) {
                etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
            }
        } catch (NumberFormatException e) {
            // 输入格式错误，标记为不一致
            etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
        }

        // 显示查询结果
        StringBuilder resultBuilder = new StringBuilder();
        for (CSVRecord record : records) {
            resultBuilder.append("物料编号: ").append(record.getMaterialId()).append("\n")
                    .append("批次号: ").append(record.getBatch()).append("\n")
                    .append("总重量: ").append(record.getGrossWeight()).append("\n")
                    .append("净重: ").append(record.getNetWeight()).append("\n")
                    .append("时间: ").append(record.getTimestamp()).append("\n\n");
        }
        tvQueryResult.setText(resultBuilder.toString());
    }

    private void searchRecordsByNumber(String materialId) {
        //  String materialId = etSearchMaterialId.getText().toString().trim();
        //   if (materialId.isEmpty()) {
        //       Toast.makeText(this, "请输入物料编号", Toast.LENGTH_SHORT).show();
        //       return;
        //   }


        UserDao userDao = new UserDao(this);
        userDao.queryByBatchNumber(materialId, new UserDao.QueryResultCallback() {
            @Override
            public void onSuccess(List<CSVRecord> records) {
                runOnUiThread(() -> {
                    if (records.isEmpty()) {
                        tvQueryResult.setText("未找到相关记录");
                        return;
                    }

                    // 获取当前输入框的值
                    String currentBatch = etbatchNumber.getText().toString().trim();
                    String currentNumber = etNumber.getText().toString().trim();
                    String currentGrossWeight = etWeight1.getText().toString().trim().replaceAll("[^\\d.]", ""); // 移除非数字字符
                    String currenttareWeight = etWeight2.getText().toString().trim().replaceAll("[^\\d.]", "");
                    String currentNetWeight = etWeight3.getText().toString().trim().replaceAll("[^\\d.]", "");

                    // 假设比较最新一条记录
                    CSVRecord latestRecord = records.get(0);
                    String recordBatch = latestRecord.getBatch();
                    String recordNumber = latestRecord.getMaterialId();
                    double recordGross = latestRecord.getGrossWeight();
                    double recordTare = latestRecord.getTareWeight();
                    double recordNet = latestRecord.getNetWeight();

                    // 重置所有输入框背景
                    resetEditTextBackgrounds();


                    // 比较批次号（字符串比较）
                    if (!currentBatch.equals(recordBatch)) {
                        etbatchNumber.setBackgroundResource(R.drawable.edittext_border_red);
                    }

                    try {
                        double Dtareweight = Double.parseDouble(currenttareWeight);
                        if (Dtareweight != recordTare) {
                            etWeight2.setBackgroundResource(R.drawable.edittext_border_red);
                        }
                    } catch (NumberFormatException e) {
                        etWeight2.setBackgroundResource(R.drawable.edittext_border_red); // ✅ 正确
                    }

                    // 比较总重量（数值比较）
                    try {
                        double currentGross = Double.parseDouble(currentGrossWeight);
                        if (currentGross != recordGross) {
                            etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
                        }
                    } catch (NumberFormatException e) {
                        // 输入格式错误，标记为不一致
                        etWeight1.setBackgroundResource(R.drawable.edittext_border_red);
                    }

                    // 比较净重（数值比较）
                    try {
                        double currentNet = Double.parseDouble(currentNetWeight);
                        if (currentNet != recordNet) {
                            etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
                        }
                    } catch (NumberFormatException e) {
                        // 输入格式错误，标记为不一致
                        etWeight3.setBackgroundResource(R.drawable.edittext_border_red);
                    }

                    StringBuilder resultBuilder = new StringBuilder();
                    for (CSVRecord record : records) {
                        resultBuilder.append("物料编号: ").append(record.getMaterialId()).append("\n")
                                .append("批次号: ").append(record.getBatch()).append("\n")
                                .append("操作员: ").append(record.getOperator()).append("\n") // 新增显示操作员
                                .append("总重量: ").append(record.getGrossWeight()).append("\n")
                                .append("净重: ").append(record.getNetWeight()).append("\n")
                                .append("时间: ").append(record.getTimestamp()).append("\n\n");
                    }
                    tvQueryResult.setText(resultBuilder.toString());
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> {
                    Toast.makeText(WeightRecordDecodeActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                    tvQueryResult.setText("查询失败");
                });
            }
        });
    }

}
